package com.roads.project.controller;

import java.util.ArrayList;
import java.util.List;

import com.roads.common.constant.Constants;
import com.roads.common.constant.UserConstants;
import com.roads.common.core.domain.entity.SysUser;
import com.roads.common.utils.SecurityUtils;
import com.roads.common.utils.StringUtils;
import com.roads.project.domain.ProCompany;
import com.roads.project.domain.ProInstitutionDetail;
import com.roads.project.domain.ProInstitutionUser;
import com.roads.project.domain.ProProject;
import com.roads.project.domain.vo.TransferUser;
import com.roads.project.service.IProCompanyService;
import com.roads.project.service.IProInstitutionUserService;
import com.roads.project.service.IProProjectService;
import com.roads.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.roads.common.annotation.Log;
import com.roads.common.core.controller.BaseController;
import com.roads.common.core.domain.AjaxResult;
import com.roads.common.enums.BusinessType;
import com.roads.project.domain.ProInstitution;
import com.roads.project.service.IProInstitutionService;
import com.roads.common.utils.poi.ExcelUtils;
import com.roads.common.core.page.TableDataInfo;

/**
 * 机构Controller
 *
 * @author nhp
 * @date 2021-11-16
 */
@RestController
@RequestMapping("/project/institution")
public class ProInstitutionController extends BaseController {

    @Autowired
    private IProInstitutionService proInstitutionService;

    @Autowired
    private IProProjectService proProjectService;

    @Autowired
    private IProCompanyService proCompanyService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IProInstitutionUserService institutionUserService;

    /**
     * 查询机构列表
     */
    @PreAuthorize("@ss.hasPermi('project:institution:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProInstitution proInstitution) {
        startPage();
        proInstitution.setCreateBy(getUsername());
        List<ProInstitution> list;
        if (SecurityUtils.isAdmin(getUserId())) {
            list = proInstitutionService.selectProInstitutionListAll(proInstitution);
        } else {
            list = proInstitutionService.selectProInstitutionList(proInstitution);
        }
        return getDataTable(list);
    }

    /**
     * 导出机构列表
     */
    @PreAuthorize("@ss.hasPermi('project:institution:export')")
    @Log(title = "机构管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ProInstitution proInstitution) {
        List<ProInstitution> list = proInstitutionService.selectProInstitutionList(proInstitution);
        ExcelUtils<ProInstitution> util = new ExcelUtils<ProInstitution>(ProInstitution.class);
        return util.exportExcel(list, "机构数据");
    }

    /**
     * 获取机构详细信息
     */
    @PreAuthorize("@ss.hasPermi('project:institution:query')")
    @GetMapping(value = { "/", "/{institutionId}" })
    public AjaxResult getInfo(@PathVariable(value = "institutionId", required = false) Integer institutionId) {
        AjaxResult ajax = AjaxResult.success();
        List<ProProject> projects = proProjectService.selectProProjectList(new ProProject());
        List<ProCompany> companys = proCompanyService.selectProCompanyList(new ProCompany());
//        List<SysUser> users = sysUserService.selectListNotAdmin();
        ajax.put("projects", projects);
        ajax.put("companys", companys);
//        ajax.put("users", users);
        if (StringUtils.isNotNull(institutionId)) {
            ProInstitution institution = proInstitutionService.selectProInstitutionByInstitutionId(institutionId);
            ajax.put(AjaxResult.DATA_TAG, institution);
            List<ProInstitution> bid = proInstitutionService.dropDownBidByProjectId(institution.getProjectId());
            ajax.put("bid", bid);
            List<ProInstitution> zdBid = proInstitutionService.dropDownZdBidByProjectId(institution.getProjectId());
            ajax.put("zdBid", zdBid);
            List<ProInstitution> jlBid = proInstitutionService.dropDownJlBidByProjectId(institution.getProjectId());
            ajax.put("jlBid", jlBid);
            List<ProInstitution> zjBid = proInstitutionService.dropDownZjBidByProjectId(institution.getProjectId());
            ajax.put("zjBid", zjBid);
            List<ProInstitution> djBid = proInstitutionService.dropDownDjBidByProjectId(institution.getProjectId());
            ajax.put("djBid", djBid);
            List<ProInstitution> yzBid = proInstitutionService.dropDownYzBidByProjectId(institution.getProjectId());
            ajax.put("yzBid", yzBid);
        }
        return ajax;
    }

    /**
     * 获取机构详细信息
     */
    @PreAuthorize("@ss.hasPermi('project:institution:query')")
    @GetMapping(value = "/browse/{institutionId}")
    public AjaxResult getBrowse(@PathVariable("institutionId") Integer institutionId) {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(institutionId)) {
            ProInstitution institution = proInstitutionService.selectProInstitutionByInstitutionId(institutionId);
            ajax.put(AjaxResult.DATA_TAG, institution);
            ProInstitutionDetail detail = proInstitutionService.getDetailModelByInnerCode(institution.getInnerCode());
            ajax.put("detail", detail);
        }
        return ajax;
    }

    @GetMapping(value = "/dropDownBidByProjectId/{projectId}")
    public AjaxResult dropDownBidByProjectId(@PathVariable("projectId") Integer projectId) {
        AjaxResult ajax = new AjaxResult();
        List<ProInstitution> bid = proInstitutionService.dropDownBidByProjectId(projectId);
        ajax.put("bid", bid);
        List<ProInstitution> zdBid = proInstitutionService.dropDownZdBidByProjectId(projectId);
        ajax.put("zdBid", zdBid);
        List<ProInstitution> jlBid = proInstitutionService.dropDownJlBidByProjectId(projectId);
        ajax.put("jlBid", jlBid);
        List<ProInstitution> zjBid = proInstitutionService.dropDownZjBidByProjectId(projectId);
        ajax.put("zjBid", zjBid);
        List<ProInstitution> djBid = proInstitutionService.dropDownDjBidByProjectId(projectId);
        ajax.put("djBid", djBid);
        List<ProInstitution> yzBid = proInstitutionService.dropDownYzBidByProjectId(projectId);
        ajax.put("yzBid", yzBid);
        return ajax;
    }

    /**
     * 新增机构
     */
    @PreAuthorize("@ss.hasPermi('project:institution:add')")
    @Log(title = "机构管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProInstitution proInstitution) {
        if (UserConstants.NOT_UNIQUE.equals(proInstitutionService.checkInstitutionCodeUnique(proInstitution))) {
            return AjaxResult.error("新增机构'" + proInstitution.getInstitutionCode() + "'失败，机构编号已存在");
        }
        if (Constants.INSTITUTION_TYPE_F.equals(proInstitution.getInstitutionType()) && StringUtils.isEmpty(proInstitution.getParentCode())) {
            return AjaxResult.error("机构类为分包，所属标段不能为空");
        }
        proInstitution.setCreateBy(getUsername());
        ProProject project = proProjectService.selectProProjectByProjectId(proInstitution.getProjectId());
        // 分包内码由建设项目编码+标段编码+分包编码组成
        if (Constants.INSTITUTION_TYPE_F.equals(proInstitution.getInstitutionType())) {
            ProInstitution bid = proInstitutionService.getModelByInnerCode(proInstitution.getParentCode());
            proInstitution.setInnerCode(project.getProjectCode() + "-" + bid.getInstitutionCode() + "-" + proInstitution.getInstitutionCode());
        } else {
            proInstitution.setInnerCode(project.getProjectCode() + "-" + proInstitution.getInstitutionCode());
        }
        return toAjax(proInstitutionService.insertProInstitution(proInstitution));
    }

    /**
     * 修改机构
     */
    @PreAuthorize("@ss.hasPermi('project:institution:edit')")
    @Log(title = "机构管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProInstitution proInstitution) {
        ProProject project = proProjectService.selectProProjectByProjectId(proInstitution.getProjectId());
        if (UserConstants.NOT_UNIQUE.equals(proInstitutionService.checkInstitutionCodeUnique(proInstitution))) {
            return AjaxResult.error("修改机构'" + proInstitution.getInstitutionCode() + "'失败，机构编号已存在");
        }
        if (Constants.INSTITUTION_TYPE_F.equals(proInstitution.getInstitutionType()) && StringUtils.isEmpty(proInstitution.getParentCode())) {
            return AjaxResult.error("机构类为分包，所属标段不能为空");
        }
        // 分包内码由建设项目编码+标段编码+分包编码组成
        if (Constants.INSTITUTION_TYPE_F.equals(proInstitution.getInstitutionType())) {
            ProInstitution bid = proInstitutionService.getModelByInnerCode(proInstitution.getParentCode());
            proInstitution.setInnerCode(project.getProjectCode() + "-" + bid.getInstitutionCode() + "-" + proInstitution.getInstitutionCode());
        } else {
            proInstitution.setInnerCode(project.getProjectCode() + "-" + proInstitution.getInstitutionCode());
        }
        proInstitution.setUpdateBy(getUsername());
        return toAjax(proInstitutionService.updateProInstitution(proInstitution));
    }

    /**
     * 删除机构
     */
    @PreAuthorize("@ss.hasPermi('project:institution:remove')")
    @Log(title = "机构管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{institutionIds}")
    public AjaxResult remove(@PathVariable Integer[] institutionIds) {
        return toAjax(proInstitutionService.deleteProInstitutionByInstitutionIds(institutionIds));
    }

    /**
     * 获取机构用户
     *
     * @param innerCode 机构内部编码
     * @return
     */
    @PostMapping("/getInstitutionUserList")
    public AjaxResult getInstitutionUserList(String innerCode) {
        AjaxResult ajax = new AjaxResult();
        List<SysUser> sysUsers = sysUserService.selectListNotAdmin();
        List<TransferUser> users = new ArrayList<>();
        for (SysUser sysUser : sysUsers) {
            TransferUser user = new TransferUser();
            user.setUser(sysUser.getUserName());
            user.setName(sysUser.getNickName());
            user.setProjectId(sysUser.getProjectId());
            if (StringUtils.isNotEmpty(sysUser.getInstitutionCode()) && sysUser.getInstitutionCode().equals(innerCode)) {
                user.setDisabled(true);
            }
            users.add(user);
        }
        List<ProInstitutionUser> checkedUsers = institutionUserService.selectUserByCode(innerCode);
        List<String> userList = new ArrayList<>();
        if (checkedUsers.size() > 0) {
            for (ProInstitutionUser user: checkedUsers) {
                userList.add(user.getUserName());
            }
        }
        ajax.put("users", users);
        ajax.put("checkedUsers", userList);
        return ajax;
    }

    @PostMapping("/saveInstitutionUser")
    public AjaxResult saveInstitutionUser(String innerCode, String users) {
        return toAjax(institutionUserService.saveInstitutionUser(innerCode, users));
    }


    /**
     * 获取机构详细信息
     */
    @GetMapping(value = {"/getInstitutionDetail/{institutionId}" })
    public AjaxResult getInstitutionDetail(@PathVariable(value = "institutionId", required = false) Integer institutionId) {
        ProInstitutionDetail detail = proInstitutionService.getInstitutionDetailById(institutionId);
        return AjaxResult.success(detail);
    }

    /**
     * 获取工程量清单小数位数
     */
    @GetMapping(value = "/getDecimalPlace1/{institutionCode}")
    public AjaxResult getDecimalPlace1(@PathVariable("institutionCode") String institutionCode) {
        AjaxResult ajaxResult = new AjaxResult();
        ProInstitutionDetail institutionDetail = proInstitutionService.getDetailModelByInnerCode(institutionCode);
        int decimalPlace = institutionDetail.getDecimalPlace1() == null ? 0 : institutionDetail.getDecimalPlace1();
        ajaxResult.put("decimalPlace", decimalPlace);
        return ajaxResult;
    }

    /**
     * 获取计量清单小数位数
     */
    @GetMapping(value = "/getDecimalPlace2/{institutionCode}")
    public AjaxResult getDecimalPlace2(@PathVariable("institutionCode") String institutionCode) {
        AjaxResult ajaxResult = new AjaxResult();
        ProInstitutionDetail institutionDetail = proInstitutionService.getDetailModelByInnerCode(institutionCode);
        int decimalPlace = institutionDetail.getDecimalPlace2() == null ? 0 : institutionDetail.getDecimalPlace2();
        ajaxResult.put("decimalPlace", decimalPlace);
        return ajaxResult;
    }

    /**
     * 修改机构详情
     */
    @PreAuthorize("@ss.hasPermi('project:institution:edit')")
    @Log(title = "标段详情", businessType = BusinessType.UPDATE)
    @PutMapping("/updateInstitutionDetail")
    public AjaxResult editDetail(@RequestBody ProInstitutionDetail detail) {
        detail.setUpdateBy(getUsername());
        return toAjax(proInstitutionService.updateInstitutionDetail(detail));
    }

}
